import {defineStore} from 'pinia';
import {ref} from 'vue';
import {adminLogin, adminRegister} from '@/router/api.js';
import {useRouter} from 'vue-router';
import {decodeToken} from "@/utils/JwtUtil.js";

export const adminUserStore = defineStore('admin', () => {
    const router = useRouter();
    const adminInfo = ref({
        id: '',
        account: '',
        password: '',
        status: '',
        last_login_time: '',
        last_login_ip: '',
    });
    const token = ref(null);
    const errorMessage = ref(null);
    const isLogin = ref(false);

    // 登录成功后的处理逻辑
    const handleLoginSuccess = (data) => {
        token.value = data.token;
        adminInfo.value = data.info;
        errorMessage.value = null;
    };

    // 登录方法
    const login = async (credentials) => {
        try {
            const response = await adminLogin(credentials);
            const {status, data, message} = response;
            if (status === 'error') {
                errorMessage.value = message;
                throw new Error(message);
            }

            handleLoginSuccess(data);
            isLogin.value = true;
            // 登录成功后跳转到首页
            await router.push('/adminDashboard');
        } catch (err) {
            // 捕获到后端的错误信息时，更新 errorMessage
            errorMessage.value = err.response?.data?.message || err.message || '登录失败';
            throw err;
        }
    };
    const register = async (credentials) => {
        try {
            const response = await adminRegister(credentials);
            const {status, message} = response;
            if (status === 'error') {
                errorMessage.value = message;
                throw new Error(message);
            }
        } catch (error) {
            // 错误处理
            errorMessage.value = err.response?.data?.message || '注册失败';
            throw err;
        }
    }

    const logout = () => {
        localStorage.removeItem('admin');
        sessionStorage.removeItem('admin');
        token.value = null;
        adminInfo.value = null;
        isLogin.value = false;
    }

    // 添加校验方法
    const checkTokenExpiration = () => {
        if (!token.value) return false
        const decoded = decodeToken(token.value)
        if (!decoded || Date.now() > decoded.exp) {
            logout()
            return false
        }
        return true
    }
    return {adminInfo, token, errorMessage, login, register, logout, isLogin,checkTokenExpiration};
}, {
    persist: {
        enabled: true,
        strategies: [
            {
                key: 'admin',
                storage: sessionStorage,
                paths: ['token', 'adminInfo'],
                /*serializer: {
                    // 💡 可选加密
                    serialize: (value) => encrypt(JSON.stringify(value)),
                    deserialize: (value) => JSON.parse(decrypt(value))
                }*/
            },
        ],
    },
});
